package jp.sourceforge.akjrcp.flvtools.explorer;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import jp.sourceforge.akjrcp.akj_betas.Akj_betasPlugin;
import jp.sourceforge.akjrcp.flvtools.basic.FFMpegPage;
import jp.sourceforge.akjrcp.util.MD5Util;
import jp.sourceforge.akjrcp.util.ProcessMonitor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;

public class ThumbnailManager {
	public static Log log=LogFactory.getLog(ExplorerView.class);
	public static File baseDirectory=new File(System.getProperty("user.dir")+"\\"+"thumbs");
	
	public static long expiretime=((long)1000)*60*60*24*90; //one day.
	public static Image loadThumbnail(File file){
		return loadThumbnail(file,null);
	}
	public static Image loadThumbnail(File file,Image noimg){
		log.info("base file:"+file.getAbsolutePath());
		if(!isExistThumbnail(file)){
			makeThumbnail(file);
		}
		//maybe can't made;
		File thumbFile=toThumbnailPath(file);
		if(!thumbFile.exists()){
			return noimg;
		}
		return new Image(Display.getCurrent(),thumbFile.getAbsolutePath());
	}
	
	public static void clearThumbnails(){
		
		String list[]=getThumbs();
		if(list==null){
			log.warn("file not found "+ baseDirectory);
		}
		log.info("expire:"+expiretime);
		for (int i = 0; i < list.length; i++) {
			File file=new File(list[i]);
			if((file.lastModified()+expiretime)<System.currentTimeMillis()){
				log.info("delete:"+file.getAbsolutePath()+new Date(file.lastModified()+expiretime)+" last="+new Date(System.currentTimeMillis()));
				file.delete();
			}
		}
	}
	
	public static void clearThumbnails(String keepFiles[]){
		ArrayList array=new ArrayList();
		String list[]=getThumbs();
		if(list==null){
			log.warn("file not found "+ baseDirectory);
		}
		for (int i = 0; i < list.length; i++) {
			//log.info("thumb-add:"+list[i]);
			array.add(list[i]);
		}
		for (int i = 0; i < keepFiles.length; i++) {
			String thumb=toThumbnailPath(new File(keepFiles[i])).getAbsolutePath();
			array.remove(thumb);
		}
		log.info("array-length:"+array.size());
		String[] deleteFiles=(String[]) array.toArray(new String[0]);
		for (int i = 0; i < deleteFiles.length; i++) {
			boolean b=new File(deleteFiles[i]).delete();
			if(b){
				log.info("delete file:"+deleteFiles[i]);
			}else{
				log.warn("delete faild:"+deleteFiles[i]);
			}
		}
	}
	public static String[] getThumbs(){
		ArrayList array=new ArrayList();
		if(baseDirectory.exists()){//for if thumbs not found.
		String list[]=baseDirectory.list();
		
		for (int i = 0; i < list.length; i++) {
			File tmp=new File(baseDirectory,list[i]);
			if(tmp.isFile() && tmp.getName().endsWith(".jpg")){
				array.add(tmp.getAbsolutePath());
			}
		}
		}
		return (String[]) array.toArray(new String[0]);
	}
	
	public static void debugArray(String[] array){
		String v="";
		for (int i = 0; i < array.length; i++) {
			v+="\""+array[i]+"\""+" ";
		}
		Akj_betasPlugin.getDefault().getProcessPrinter().printOutput(v+"\n");
	}
	
	public static void makeThumbnail(File file){
		
		ProcessMonitor monitor=null;
		Runtime runtime=Runtime.getRuntime();
		ArrayList param=new ArrayList();
		IPreferenceStore store=Akj_betasPlugin.getDefault().getPreferenceStore();
		
		String ffmpegPath=store.getString(FFMpegPage.FFMPEG_PATH);
		
		//check ffmpeg exist
		File ffmpegFile=new File(ffmpegPath);
		if(!ffmpegFile.exists()){
			log.warn("ffmpeg not found");
			return;
		}
		
		param.add(ffmpegPath);
		param.add("-i");
		
		param.add(file.getAbsolutePath());
		
		param.add("-f");
		param.add("image2");
		param.add("-ss");
		param.add("00:00:05");
		param.add("-vframes");
		param.add("1");
		
		param.add("-s");
		param.add("160x120");
		
		param.add(toThumbnailPath(file).getAbsolutePath());
		try {
			String arg[]=(String[])param.toArray(new String[0]);
			debugArray(arg);
			Process p=runtime.exec(arg);
			
			monitor=new ProcessMonitor(p,Akj_betasPlugin.getDefault().getProcessPrinter());
			monitor.startMonitor();
			
			
			try {
				p.waitFor();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public static boolean isExistThumbnail(File file){
		return toThumbnailPath(file).exists();
	}
	
	public static File toThumbnailPath(File file){
		return new File(baseDirectory,file.length()+"_"+file.lastModified()+"_"+MD5Util.getMD5(file,256)+".jpg");
	}

}
